package thesis.filesharing.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import thesis.filesharing.bo.LecturerBO;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.web.viewmodel.UpdateLecturerInfoViewModel;

public class UpdateLecturerInfoValidator implements Validator {
	
	@Autowired
	private LecturerBO lecturerBO;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return UpdateLecturerInfoViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lecturerName", "lecturerName.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lecturerEmail", "lecturerEmail.required");
		
		UpdateLecturerInfoViewModel model = (UpdateLecturerInfoViewModel) target;
		
		if (model.getLecturerEmail() != null && model.getLecturerEmail().length() > 0) {
			Pattern emailPattern = Pattern.compile(Constants.EMAIL_PATTERN);
			Matcher emailMatcher = emailPattern.matcher(model.getLecturerEmail());
			if (!emailMatcher.matches()) {
				errors.rejectValue("lecturerEmail", "lecturerEmail.incorrectFormat");
			}
		}
		
		if ("NONE".equalsIgnoreCase(model.getDepartment())) {
			errors.rejectValue("department", "department.required");
		}
		
		if (!errors.hasErrors()) {
			if (lecturerBO.isEmailDuplicatedWithOrtherLecturer(model.getLecturerEmail(), model.getLecturerKey())) {
				errors.reject("lecturerEmail.exists");
			}
		}
	}
}
